package com.fruit.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.codec.binary.Base64;

import net.coobird.thumbnailator.Thumbnails;

/**
 * PicUtil
 * @author Administrator 说明：日期处理 创建人：FH Q313596790
 * @version 2017.12.01 11:40
 */
public class PicUtil {

	/**
	 * base64ToInputStream
	 * @param strBase64 strBase64
	 * @param isCut isCut
	 * @return InputStream
	 * @author Administrator 说明：日期处理 创建人：FH Q313596790
	 * @version 2017.12.01 11:40
	 */
	public static InputStream base64ToInputStream(String strBase64, boolean isCut) {
		if (strBase64 == null) {
			return null;
		}
		try {
			byte[] b = Base64.decodeBase64(strBase64.split(",")[1]);
			InputStream sbs = new ByteArrayInputStream(b);
			if (isCut) {
				InputStream sbsn = cutImage(sbs, 200, 200);
				return sbsn;
			}

			return sbs;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 压缩图片
	 * @param ins ins
	 * @param width width
	 * @param height height
	 * @return InputStream
	 * @author Administrator 说明：日期处理 创建人：FH Q313596790
	 * @version 2017.12.01 11:40
	 */
	public static InputStream cutImage(InputStream ins, int width, int height) {
		if (ins == null) {
			return null;
		}
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			Thumbnails.of(ins).size(width, height).toOutputStream(out);
			InputStream sbsn = new ByteArrayInputStream(out.toByteArray());

			return sbsn;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}

		}

	}

}
